<?php

if(!defined('IN_ADAGPS'))
{
    die(SYSTEM_ACCESS_DENIED);
}
$objXajax->registerFunction('fmfrmmanager_loadMenu');      
$objXajax->registerFunction('fmfrmmanager_loadGrid');      
$objXajax->registerFunction('fmfrmmanager_checkedRoom');

$objXajax->registerFunction('fmfrmmanager_addRemoveProduct');
$objXajax->registerFunction('fmfrmmanager_moveRoom');
$objXajax->registerFunction('fmfrmmanager_loadProduct');
$objXajax->registerFunction('fmfrmmanager_finishRoom');
$objXajax->registerFunction('fmfrmmanager_closeRoom');

$objXajax->registerFunction('fmfrmmanager_addNewProduct');
$objXajax->registerFunction('fmfrmmanager_ajxTotalRoom');
$objXajax->registerFunction('fmfrmmanager_undo');
$objXajax->registerFunction('fmfrmmanager_loadRoom');
$objXajax->registerFunction('fmfrmmanager_rentRoom');
$objXajax->registerFunction('fmfrmmanager_showBill');
$objXajax->registerFunction('fmfrmmanager_save');
$objXajax->registerFunction('fmfrmmanager_init');
$objXajax->registerFunction('fmmanager_deleteproduct');

/*
* ham dung cho left menu
* 
*/
//global $fmpromotype;

function fmfrmmanager_init(){
    global $objDbSelect,$lang,$arrMenu,$arrdetail,$hotel_id;
    $objResponse = new xajaxResponse();
    
    $sql= "select fm_print,fm_greeting_bill,fm_name_service,fm_start_bill ,fm_cancelbtn,fm_undobtn,fm_undotime,fm_column from cus_config WHERE service_id = '$hotel_id'";    
     
    $arr= $objDbSelect->GetArray($sql);
    $showprintbtn=$arr[0]['fm_print'] ;
    $fm_cancelbtn=$arr[0]['fm_cancelbtn'] ;
    $fm_undobtn=$arr[0]['fm_undobtn'] ;
    $fm_undotime=$arr[0]['fm_undotime'] ;
    $fm_greeting_bill=addslashes($arr[0]['fm_greeting_bill']) ;
    $fm_start_bill    = addslashes($arr[0]['fm_start_bill']) ;
    $fm_name_service  = addslashes($arr[0]['fm_name_service']) ;
    
    $fm_column=$arr[0]['fm_column'] ;
    if($_SESSION['current']['power_type_id']==POWER_CUSTOMER){
       $fm_cancelbtn =1;                                                                           
       $fm_undobtn=1;
       
    }
    $objResponse->addScript("fm_obj.assignConfig($showprintbtn,'$fm_greeting_bill',$fm_cancelbtn,$fm_undobtn,$fm_undotime,'$fm_start_bill','$fm_name_service');");
  
    $sqlFilmPromotion = "select id,name as name,percent,type,flg_promotion from fm_promotion WHERE service_id = $hotel_id ";
    
    $arrPromotion = $objDbSelect->GetArray($sqlFilmPromotion); 
    for($i=0;$i<count($arrPromotion);$i++){
        $id = $arrPromotion[$i]['id'];
        $percent = $arrPromotion[$i]['percent'];
        $name = $arrPromotion[$i]['name'];
        $type = $arrPromotion[$i]['type'];
        $flg_promotion = $arrPromotion[$i]['flg_promotion'];
        $objResponse->addScript("fm_obj.arrPromotion[$id]= new Object();"); 
        $objResponse->addScript("fm_obj.arrPromotion[$id].percent= '$percent';"); 
        $objResponse->addScript("fm_obj.arrPromotion[$id].name= '$name';");   
        $objResponse->addScript("fm_obj.arrPromotion[$id].type= '$type';");  
        $objResponse->addScript("fm_obj.arrPromotion[$id].flg_promotion= '$flg_promotion';");  
    }
    
    $sqlFilmPromotion = "select id,name as name,percent,type from fm_promotion WHERE service_id = $hotel_id and active = 1 ";
    
    $arrPromotion = $objDbSelect->GetArray($sqlFilmPromotion);
    
    $sqlStaff = "select id,if(alias_name='' or alias_name is null,name,alias_name) as name from cus_staff WHERE active = 1 and service_id = $hotel_id and service_type = ".SVT_FILM;
   $arrStaff = $objDbSelect->GetArray($sqlStaff);

    
    $oTbs1 = new clsTinyButStrong();    
    $oTbs1->LoadTemplate('templates/'.$lang.'/customer/fm_manager_viewpromotion.html');   
    $oTbs1->MergeBlock('blk_promotion', $arrPromotion);
    
    $oTbs2 = new clsTinyButStrong();    
    $oTbs2->LoadTemplate('templates/'.$lang.'/customer/fm_manager_viewstaff.html');   
    $oTbs2->MergeBlock('blk_staff', $arrStaff);

    $oTbs1->Show(TBS_NOTHING);
    $oTbs2->Show(TBS_NOTHING);
  
    $objResponse->addAssign('fmfrmmanager_tdpromotion', 'innerHTML', $oTbs1->Source);  
    $objResponse->addAssign('fmfrmmanager_tdstaffs', 'innerHTML', $oTbs2->Source);  
    
    $objResponse->addScript("xajax_fmfrmmanager_loadGrid('$fm_column');");                       
                           
    return $objResponse->getXML();
}

function fmfrmmanager_loadMenu(){     

    global $lang,$arrMenu,$arrdetail;
    $objResponse = new xajaxResponse();
    $arr = array();
    $arrdetail= array();
    $arrMain = common_getMenu($arr,$arrdetail); 
      
    $oTbs = new clsTinyButStrong();
    $oTbs ->LoadTemplate("templates/$lang/customer/fm_manager_menu_grid.html");
    $oTbs->MergeBlock('blk_list', $arrMain);
    $oTbs->MergeBlock('blk_list1', 'array', 'arrdetail[%p1%]');
        
    $objResponse->addAssign('fmfrmmanager_leftmenu', 'innerHTML', $oTbs->Source);
     
    $count = count($arr);
    for($i=0;$i<$count;$i++){ // 
        $name     = $arr[$i]['name'];
        $price    = $arr[$i]['price'];
        $id       = $arr[$i]['id'];
        $unit     = $arr[$i]['unit'];
        $unitname = $arr[$i]['unitname'];
        $objResponse->addScript("fm_obj.createAssignProductPrice($id,'$name','$price','$unit','$unitname');"); 
    }
    $indexNewProduct = time();
    $objResponse->addScript("fm_obj.indexNewProduct=$indexNewProduct;");                            

    $objResponse->addScript("fmfrmmanager_dropdrapmenu();");                           
     $objResponse->addScript('$("div.fm_divProduct").droppable("disable");');
     $objResponse->addScript("changeWaiting(1);");                             
                          
    return $objResponse->getXML();
}

function fmfrmmanager_loadRoom(){ 
    global $lang,$arrDetail,$objDbSelect;
        $objResponse = new xajaxResponse();// dong luon luon co khi goi ham ajax
        $arrDetail = fmfrmmanager_getRoomInit();
        for($i=0;$i<count($arrDetail);$i++){
            $id = $arrDetail[$i]['id'];
            $name = $arrDetail[$i]['name'];
            $type = $arrDetail[$i]['type_id'];            
            $timestamp = $arrDetail[$i]['timestamp'];
            $promotion= $arrDetail[$i]['promotion'];
            
            $staff_id= $arrDetail[$i]['staff_id'];
            $timerent= $arrDetail[$i]['timerent'];
            
            $num_voucher= $arrDetail[$i]['num_voucher'];
            $arising_price= $arrDetail[$i]['arising_price'];
            $minmoney= $arrDetail[$i]['minmoney'];
            
            $arising_description= addslashes($arrDetail[$i]['arising_description']) ;
            
            $current_id = $arrDetail[$i]['current_id']==''?0:$arrDetail[$i]['current_id'];
            
            $status = $timestamp>0?1:0;
            if($status==1){
                $objResponse->addScript("fmfrmmanager_ActiveStatus($id);"); 
            }
            $objResponse->addScript("fm_obj.createAssignRoomObj($id,'$name','$type','$status','$timestamp',
            '$current_id','$promotion','$num_voucher','$staff_id','$timerent',
            '$arising_price','$arising_description','$minmoney');"); 
        }
        $objResponse->addScript('fmAssignTime();');
    return $objResponse->getXML(); // dong luon luon co khi goi ham ajax   
}

function fmfrmmanager_loadGrid($col){     

    global $lang,$arrMenu,$arrDetail,$hotel_id,$objDbSelect;
    $objResponse = new xajaxResponse();// dong luon luon co khi goi ham ajax
    $arrDetail = array();
    $arrRoom = fmfrmmanager_getRoom($arrDetail);

    $oTbs = new clsTinyButStrong();    
    //echo  $col; die();
    $oTbs->LoadTemplate('templates/'.$lang."/customer/fm_manager_grid_$col.html");   
    $oTbs->MergeBlock('blk_total', $arrRoom); 
    
    $oTbs->MergeBlock('blk_data', 'array', 'arrDetail[%p1%]'); 
    

    $oTbs->Show(TBS_NOTHING);
    $objResponse->addAssign('fmfrmmanager_divGrid', 'innerHTML', $oTbs->Source);
    $objResponse->addScript("addJsContext();");  
     
   $objResponse->addScript('$(".clsbtn_fm").button();');          
   $objResponse->addScript('$(".fm_chkHide").button();');          
   $objResponse->addScript('xajax_fmfrmmanager_loadMenu();'); 
   $objResponse->addScript("setTimeout('fmfrmmanager_firstload()',2000);");           
   $objResponse->addScriptCall("fmfrmmanager_checkundobtn();");        
 
             
    return $objResponse->getXML(); // dong luon luon co khi goi ham ajax   
}

function  fmfrmmanager_getRoom(&$arrDetail){
    global $objDbSelect,$tbl_postfix,$hotel_id;
    $arrResult = array();
    $sqlSelect = "SELECT r.id,r.room_type,r.name,t.style as color,t.name  as name_type,t.id as type_id
    FROM fm_room as r join fm_room_type  as t on r.room_type=t.id and t.service_id = $hotel_id where r.active = 1 and t.active = 1
     order by r.room_type,r.name";
    $arr =  $objDbSelect->GetArray($sqlSelect);
    for($i=0;$i<count($arr);$i++){
        $type_id = $arr[$i]['type_id'];
        $arrResult[$type_id]= array('type_id'=>$arr[$i]['type_id'],'name_type'=>$arr[$i]['name_type']);
        $arrDetail[$type_id][]=array('id'=>$arr[$i]['id'],'color'=>$arr[$i]['color'],'name'=>$arr[$i]['name']);
    }
    return $arrResult;
}
/*
*
* 
*/
function  fmfrmmanager_getRoomInit(){
    global $objDbSelect,$tbl_postfix,$hotel_id;
    $arrResult = array();
    $sqlSelect = "SELECT r.id,r.name as name,r.room_type,t.minmoney,t.style ,t.name  as name_type,t.id as type_id,c.id as current_id,
    if(c.timestart is not null or c.timestart <> '',TIMESTAMPDIFF(SECOND,c.timestart,now()),0) as timestamp,
    c.promotion,c.staff_id,DATE_FORMAT(c.timestart,'%Hh%i') as timerent,num_voucher,arising_price,arising_description
    FROM fm_room as r join fm_room_type  as t on r.room_type=t.id  and t.service_id = $hotel_id left join 
    fm_current_book$tbl_postfix as c on c.room_id = r.id and flgcal=0 and c.flg_cancel = 0 join cus_config cf on 
    cf.service_id = $hotel_id where r.active = 1  order by r.room_type,r.name";
    $arr =  $objDbSelect->GetArray($sqlSelect);
    return $arr;
}   

function fmfrmmanager_addRemoveProduct($arrAddRemove,$arrProduct=''){
     global $lang,$arrMenu,$objDbSelect;
     $objResponse = new xajaxResponse();

         for($i=0;$i<count($arrAddRemove);$i++){
             $temp = $arrAddRemove[$i];
             $arrId = explode(';',$temp);
             $product_id = $arrId[0];
             $nump = $arrId[2];
             $general_id = $arrId[1];
             
             $flg = fmfrmmanager_actionDB($general_id,$product_id,$nump,$arrProduct) ;
             if(!$flg){
                 $objResponse->addScript("fmfrmmanager_reloadform('Phòng đã tính tiền!');");  
             }
         }    

     return $objResponse->getXML();    
}

function fmfrmmanager_actionDB($general_id,$product_id,$nump,$arrProduct){
  global $objDbSelect,$tbl_postfix,$user_id;
  //$service_type =  SVT_FILM;
           $sqlcheck = "select flgcal  from fm_current_book$tbl_postfix where id = $general_id and flg_cancel = 0";
    $arrChk=$objDbSelect->GetArray($sqlcheck);
    if($arrChk[0]['flgcal']==0){
       $sqlSelect = "select num from cus_history_product$tbl_postfix where general_id =  
     '$general_id' and product_id = '$product_id' ";
     $arrSelect = $objDbSelect->GetArray($sqlSelect);
     $sql ='';
     if(is_array($arrSelect) && count($arrSelect)==1){
         $curnum =  $arrSelect[0]['num'];// 
         $nextnum = $curnum + $nump;
         if($nextnum<1){
             $sql= "delete from cus_history_product$tbl_postfix where general_id =  
     '$general_id' and product_id = '$product_id'  ";   
     // write log........................
         }else{
            $sql = "update cus_history_product$tbl_postfix SET num = '$nextnum' where general_id =  
     '$general_id' and product_id = '$product_id' ";     
      // write log........................ 
         }
     }else{
        $name = $arrProduct[$product_id]['name'];
        $price = $arrProduct[$product_id]['price'];
        $sql = "insert into cus_history_product$tbl_postfix(general_id,product_id,name,price,date_created,user_created,num) 
        values('$general_id','$product_id','$name','$price',now(),'$user_id',$nump)"; 
       // write log........................   
     }   
    }else{
        return false;
        //$objResponse->addScript("fmfrmmanager_reloadform('Phòng đã tính tiền!');");    
    }
     
     $objDbSelect->Execute($sql);  
     return true;
}

function fmfrmmanager_moveRoom($RoomFrom,$RoomTo,$typeFrom,$typeTo){
    global $objDbSelect,$tbl_postfix,$user_id;
    $objResponse = new xajaxResponse();
    $update = '';
    $sqlcheck = "select count(id) as cnt  from fm_current_book$tbl_postfix where room_id = $RoomFrom and flgcal =0 and flg_cancel = 0 ";
    $arrChkFrom=$objDbSelect->GetArray($sqlcheck);
    $cntFrom = $arrChkFrom[0]['cnt'];// Đếm coi phải phòng này đang trống hay ko    
    
    $sqlcheck = "select count(id) as cnt  from fm_current_book$tbl_postfix where room_id = $RoomTo and flgcal =0 and flg_cancel = 0";
    $arrChkTo=$objDbSelect->GetArray($sqlcheck);
    $cntTo = $arrChkTo[0]['cnt'];// Đếm coi phải phòng này đang trống hay ko
    if($cntFrom==1 && $cntTo==0){
         if($typeFrom!=$typeTo){
        $update = ",timestart = now()";
        $sqlselect = " select id as general_id,timestart as timefrom,now() as timeto, TIMESTAMPDIFF(MINUTE,timestart,now()) as renttime from fm_current_book$tbl_postfix where room_id = '$RoomFrom' and flgcal = 0 and flg_cancel = 0 ";
        $arr =  $objDbSelect->GetArray($sqlselect);
        $timefrom  = $arr[0]['timefrom'];
        $timeto    = $arr[0]['timeto'];
        $general_id    = $arr[0]['general_id'];
        $renttime    = $arr[0]['renttime'];
        $price     = fm_calTotal($timefrom,$timeto,$typeFrom);
        $sql = " insert into tbl_history_move$tbl_postfix(general_id, room_id, user_created, date_created, price, timestart,renttime)
        values($general_id,$RoomFrom,$user_id,now(),'$price','$timefrom',$renttime) ";
        $objDbSelect->Execute($sql); 
    }
    $sql = " update fm_current_book$tbl_postfix set room_id = $RoomTo ,user_update = '$user_id', date_update = now() $update where room_id  = $RoomFrom and flgcal = 0 and flg_cancel = 0 ";
    $objDbSelect->Execute($sql); 
            
    }else{
        $strAlert='';
        if($cntFrom==0){
           $strAlert='Phòng chuyển đi hiện không hoạt động!'; 
        }else{
           $strAlert='Phòng chuyển đến đang hoạt động!';  
        }
        $objResponse->addScript("fmfrmmanager_reloadform('$strAlert');");    
    }
   
        
    return $objResponse->getXML();  
}
/*
* HÃ m nÃ y dÃ¹ng Ä‘á»ƒ load product lÃªn cÃ¡c bÃ n 
* 
* 
*/
function fmfrmmanager_loadProduct(){
    global $objDbSelect,$tbl_postfix;
     $objResponse = new xajaxResponse();
    // $service_type =  SVT_FILM;
    $sql = "select c.room_id,p.name,p.price,p.num,p.product_id from cus_history_product$tbl_postfix as p
JOIN fm_current_book$tbl_postfix as c ON c.id = p.general_id  and c.flgcal = 0 and p.num>0 and c.flg_cancel = 0 order by p.date_created"; // lấy sản phẩm trên bàn từ DB
    $arr = $objDbSelect->GetArray($sql);
    for($i=0;$i<count($arr);$i++){
        $room_id = $arr[$i]['room_id'];
        $name = addslashes($arr[$i]['name']); 
        $num = $arr[$i]['num'];
        $price = $arr[$i]['price'];
        $product_id = $arr[$i]['product_id'];
        $objResponse->addScript("fmfrmmanager_loadProduct('$room_id','$product_id','$name','$num','$price');"); // load cÃ¡c sáº£n pháº©m Ä‘Ã³ lÃªn bÃ n
    }
     $objResponse->addScript("fm_addJsContext();"); 
   return $objResponse->getXML();  
}
/*
* hÃ m nÃ y dÃ¹ng Ä‘á»ƒ tÃ­nh toÃ¡n khi khÃ¡ch hÃ n kÃªu tÃ­nh tiá»?n  
* @room_id : id cá»§a bÃ n cáº§n tÃ­nh 
* $current_id : id Ä‘i cá»§a bÃ n mÆ°á»›n hiá»‡n hÃ nh
* $pricehour : tiá»?n giá»?
* $pricetotal : toÃ n bá»™ tiá»?n cá»§a phÃ²ng
*/
function fmfrmmanager_finishRoom($params){    
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    
    $current_id=$params['current_id'] ;
    $pricehour=$params['pricehour'] ;
    $pricetotal=$params['pricetotal'] ;
    $priceproduct=$params['priceproduct'] ;
    $room_id=$params['room_id'] ;
    $pricevoucher=$params['pricevoucher']  ==''?0:-$params['pricevoucher'] ; 

    //$priceproduct =$pricetotal-$pricehour ;
    
    $sql = " update fm_current_book$tbl_postfix SET timeend=now(),flgcal =1,money_rent='$pricehour',total='$pricetotal',
    user_update = $user_id, date_update = now(),
    price_voucher = '$pricevoucher' where id = $current_id";
    if($objDbSelect->Execute($sql)){
        $objResponse->addScript("$('#fmfrmmanager_divprint').dialog('close');");
        $objResponse->addScript("fmfrmmanager_DeactiveStatus($room_id);");
        $objResponse->addScript("fm_obj.resetRoom($room_id);");
        $objResponse->addScript("$('#fmfrmmanager_div_$room_id').find('.trProduct').remove();");
    }
    $objResponse->addScript("fm_calActiveTableByTableType();");
    return $objResponse->getXML();
}
/*
* HÃ m nÃ y dÃ¹ng Ä‘á»ƒ add sáº£n pháº©m ngoÃ i doanh má»¥c 
* $proId : láº¥y id tá»« indexproduct
* $hdtRoom : id cá»§a bÃ n thÃªm sáº£n pháº©m má»›i
* $name : tÃªn sáº£n pháº©m 
* $price : giÃ¡ cá»§a sáº£n pháº©m ngoÃ i doanh má»¥c
*/
function fmfrmmanager_addNewProduct($proId,$hdRoom,$name,$price,$general_id=''){
    global $objDbSelect,$user_id,$hotel_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $sql =''; 
    $service_type = SVT_FILM;
    $sqlcheck = "select count(id) as cnt  from fm_current_book$tbl_postfix where room_id = $hdRoom and flgcal =0 and flg_cancel = 0";
    $arrChk=$objDbSelect->GetArray($sqlcheck);
    if($arrChk[0]['cnt']==1){
        if($general_id ==''){
        $sqlsel = "select id from fm_current_book$tbl_postfix where room_id = '$hdRoom' and flgcal = 0 and flg_cancel = 0" ;
        $arr = $objDbSelect->GetArray($sqlsel);
        $general_id = $arr[0]['id'];
    }
    $sql = "insert into cus_history_product$tbl_postfix(product_id,name,price,date_created,user_created,num,general_id) 
    values('$proId','$name','$price',now(),'$user_id',1,'$general_id')";  
     $objDbSelect->Execute($sql);  
        
    }else{
      $objResponse->addScript("fmfrmmanager_reloadform('Phòng đã tính tiền!');");  
    }
    
    return $objResponse->getXML();    
}

function fmfrmmanager_undo($room_id,$undotime){
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $service_type = SVT_FILM;
    $sqlcheck = "select count(id) as cnt from fm_current_book$tbl_postfix where room_id = $room_id and flgcal=0 and flg_cancel = 0";
    $arrChk=$objDbSelect->GetArray($sqlcheck);
    if($arrChk[0]['cnt']==0){
        $sqlgeneral = " select id as general_id,TIMESTAMPDIFF(SECOND,max(timestart),now()) as renttime ,
        TIMESTAMPDIFF(MINUTE,max(timeend),now()) as period 
        from fm_current_book$tbl_postfix where id = (select max(id ) from fm_current_book$tbl_postfix where room_id=$room_id and flg_cancel = 0)    group by room_id ";
        $arrgeneral = $objDbSelect->GetArray($sqlgeneral);
        if(is_array($arrgeneral) && count($arrgeneral)>0 ){
            $period = (int)$arrgeneral[0]['period'];
        if($period>$undotime){
           $objResponse->addScript("alert('Quá thời gian cho phép phục hồi');");  
           $objResponse->addScript("$(fmfrmmanager_undo_$room_id).find('img').hide()");  
        }else{
            $timestamp = $arrgeneral[0]['renttime'];
            $general_id = $arrgeneral[0]['general_id'];

            $sql = "select * from cus_history_product$tbl_postfix where  general_id = $general_id  order by date_created"; 
            $objResponse->addScript("fm_obj.arrRoom[$room_id].status=1;"); 
            $objResponse->addScript("fm_obj.arrRoom[$room_id].timestamp=$timestamp;"); 
            $objResponse->addScript("fm_obj.arrRoom[$room_id].current_id=$general_id;"); 

            $arr = $objDbSelect->GetArray($sql);
            $sqlUpdate = "update fm_current_book$tbl_postfix set flgcal = 0,timeend=null,money_rent=0,total=0 where id = $general_id ";
            $objDbSelect->Execute($sqlUpdate);
            if(is_array($arr) && count($arr)>0){
            for($i=0;$i<count($arr);$i++){
            $name = $arr[$i]['name'];
            $num = $arr[$i]['num'];
            $price = $arr[$i]['price'];
            $product_id = $arr[$i]['product_id'];
            $objResponse->addScript("fmfrmmanager_loadProduct('$room_id','$product_id','$name','$num','$price');"); // load cac san pham
         }  
        }
            $objResponse->addScript("fm_calActiveTableByTableType();");
            $objResponse->addScript("fmfrmmanager_ActiveStatus($room_id)");
                
        }
            
        }else{
           $objResponse->addScript("alert('Không có dữ liệu để phục hồi!');");   
        }
    
    }else{
      $objResponse->addScript("fmfrmmanager_reloadform('Phòng đang hoạt động!');");  
    }
    return $objResponse->getXML();    
}

function fmfrmmanager_rentRoom($roomId){
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $sqlcheck = "select count(id) as cnt from fm_current_book$tbl_postfix where room_id = $roomId and flgcal=0 and flg_cancel = 0 ";
    $arrChk=$objDbSelect->GetArray($sqlcheck);
    if($arrChk[0]['cnt']==0){
        $sql = "INSERT into fm_current_book$tbl_postfix(timestart, room_id, first_room, user_created, date_created) VALUE(now(),'$roomId','$roomId',$user_id,now())";    
    $objDbSelect->Execute($sql);
    $current = mysql_insert_id();  
    $objResponse->addScript("fm_obj.AssignStatusRoom($roomId,1,$current);"); 
    $objResponse->addScript("fmfrmmanager_ActiveStatus($roomId)"); 
    $objResponse->addScript("fm_calActiveTableByTableType();");
    $objResponse->addScript("fm_obj.rentRoomObj('$roomId');");
        
    }else{
      $objResponse->addScript("fmfrmmanager_reloadform('Phòng đang hoạt động!');");   
    }
    
                              
    return $objResponse->getXML(); 
}

function fmfrmmanager_showBill($current_id,$Room_id,$arrConfig,$minmoney,$arrPromotion){ 
    global $objDbSelect,$user_id,$tbl_postfix,$hourPay,$hourmoney,$total,$lang,$voucherprice,
    $vouchertitle,$promotionval,$showvoucher,$arisingval,$showarising,$hourStart,$hourEnd,$priceproduct,$showProduct;
   $objResponse = new xajaxResponse();
   $sqlcheck = "select flgcal from fm_current_book$tbl_postfix where id = $current_id";
    $arrChk=$objDbSelect->GetArray($sqlcheck);
    if($arrChk[0]["flgcal"]==0){
       //$service_type = SVT_FILM;
    $sqlhour = "select c.timestart,now() as timeend,r.room_type,TIMESTAMPDIFF(SECOND,timestart,now()) as renttime 
    ,c.num_voucher,c.arising_price ,c.promotion ,c.promotion_type  from fm_current_book$tbl_postfix c join fm_room r   
    on c.room_id = r.id  JOIN fm_room_type as rt ON 
    r.room_type = rt.id where c.id = '$current_id'";
    
    $arrhour = $objDbSelect->GetArray($sqlhour);
    $from = $arrhour[0]['timestart'];
    $to = $arrhour[0]['timeend'];
    $room_type_id = $arrhour[0]['room_type'];
    $renttime = $arrhour[0]['renttime'];    
    $promotion =  $arrhour[0]['promotion'];
    $num_voucher =  $arrhour[0]['num_voucher'];
    $promotion_type =  $arrhour[0]['promotion_type'];
    $arisingval =  -$arrhour[0]['arising_price'];
    $hourStart = GetHM4Show($from);
    $hourEnd = GetHM4Show($to);
    
    $vouchertitle ='';
    $voucherprice =0; // gia voucher hoac phan tram khuyen mai
    $showvoucher = 'none'  ;    
    $showarising = 'none'  ;    
    $showProduct = 'none'  ;    
    $type = 0;
    if($promotion_type!='-1'){// promotiontype khac -1 can xem lai cho nay
       $voucherprice =$arrPromotion[$promotion]['percent'];
       $type =$arrPromotion[$promotion]['type'];
       $showvoucher='';
    }
    if($arisingval<0){
     $showarising ='';   
    }
    $hourPay=ConvertToHM($renttime); 
    $hourmoney = fm_calTotal($from,$to,$room_type_id); 
    if($hourmoney<$minmoney){
         $hourmoney =  $minmoney;
    }   
    $sql="SELECT  name, num, price * num as total,0 as style FROM cus_history_product$tbl_postfix where general_id = '$current_id'  ";
    $arr = $objDbSelect->GetArray($sql);
    $priceproduct = 0;
    for($i=0;$i<count($arr);$i++){
        $priceproduct += (int)$arr[$i]['total'];
        $showProduct ='';
    }

    $total=$hourmoney+$priceproduct+$arisingval;
   $promotionval= 0; 
    if($promotion_type>0){     
        switch($type){
            case 1:$promotionval=$voucherprice*($hourmoney+$arisingval); break;
            case 2:$promotionval=$voucherprice*$total; break;
        }
        $promotionval = -round($promotionval/100,-3);
        $total+=$promotionval;        
        $vouchertitle ='KM-'.$arrPromotion[$promotion]['name'];
        $voucherprice =$voucherprice.'%';
    }
    
    if($promotion_type==0){
       $promotionval = $voucherprice* $num_voucher;
        switch($type){
            case 1:$promotionval=($hourmoney+$phuthunguoi+$arisingval)>=$promotionval?$promotionval:$hourmoney+$phuthunguoi+$arisingval; break;
            case 2:$promotionval=($hourmoney+$phuthunguoi+$phuthukinh+$arisingval)>=$promotionval?$promotionval:$hourmoney+$phuthunguoi+$phuthukinh+$arisingval; break;
            case 3:$promotionval=$total>=$promotionval?$promotionval:$total; break;
        }
        
       $promotionval=-$promotionval;
       $total +=$promotionval;
       $vouchertitle ='V-'.$arrPromotion[$promotion]['name']; 
       $voucherprice =  $num_voucher;
    }
    
    
    $bill = 'fm_manager_bill_1.html';
    $showbutton=$arrConfig['showprintbtn'];
    if($showbutton==1){
      $bill = 'fm_manager_bill.html';    
    }
    $timebill = ConvertDate($to,true);
    //obj.assignPriceSave(current_id,pricetotal,priceproduct,pricevoucher) 
    $objResponse->addScript("fm_obj.assignPriceSave($current_id,$Room_id,$hourmoney,$total,$priceproduct,$promotionval,'$timebill')");
    $oTbs = new clsTinyButStrong();    
    $oTbs->LoadTemplate('templates/'.$lang.'/customer/'.$bill);   
    $oTbs->MergeBlock('blk_list', $arr); 
    $oTbs->Show(TBS_NOTHING);
    $objResponse->addAssign('fmfrmmanager_divprint', 'innerHTML', $oTbs->Source);
    $objResponse->addScript("$('#fmfrmmanager_divprint').dialog('open')");     
    }else{
      $objResponse->addScript("fmfrmmanager_reloadform('Phòng đã tính tiền!');");     
    }
    
    
    return $objResponse->getXML();
}

function fmfrmmanager_save($params)
{
    global $objDbSelect,$user_id,$tbl_postfix,$hotel_id;

    $objResponse =  new xajaxResponse();
    $staff_id = $params['cbbstaff'];
    $timerent = $params['hdtimerent'];
    $percent_promotion = $params['hdpromopercent'];
    $arisingPrice = $params['txtarisingPrice'];
    $txtdescription=str_replace('"',"'",$params['txtdescription']);
    $arisingDescription = addslashes($txtdescription) ;
    $promotion = $params['cbbprommotion'];
    $promotion_type = $params['hdpromotype']; 
    $numvoucher = $promotion_type!=0?0:$params['cbbnumvoucher']; 
    $id = $params['hdcurrentviewdetail'];
    $sql = ""; 
    $sql = " UPDATE fm_current_book$tbl_postfix SET staff_id = '$staff_id',promotion = '$promotion',
            promotion_type  = '$promotion_type ',percent_promotion = '$percent_promotion'
            ,num_voucher='$numvoucher',arising_price='$arisingPrice',arising_description='$arisingDescription'
             WHERE room_id =$id and flgcal = 0 and flg_cancel = 0"; 
    $objDbSelect->Execute($sql);
    
    $objResponse->addScript("fm_obj.changeRoomObj($id,'$promotion','$numvoucher','$staff_id','$timerent','$arisingPrice','$arisingDescription');");
  
    $objResponse->addScript('changeWaiting(1);');
    $objResponse->addScript("$('#fmfrmmanager_divDetail').dialog('close');");
 
    return $objResponse->getXML();
}

function fmfrmmanager_closeRoom($id,$current_id,$reason_cancel=''){
    
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $sqlcheck = "select count(id) as cnt from fm_current_book$tbl_postfix where id = '$current_id' and flgcal=0 and flg_cancel=0 ";
    $arrChk=$objDbSelect->GetArray($sqlcheck);
    $reason_cancel= addslashes($reason_cancel);
    if($arrChk[0]['cnt']==1){
       $sql = "update cus_history_product$tbl_postfix set flg_cancel=1   where general_id = '$current_id'";
        if($objDbSelect->Execute($sql)){
            $sql = "update fm_current_book$tbl_postfix set flg_cancel=1,user_cancel = '$user_id',
            reason_cancel = '$reason_cancel' ,timeend = now()  where id = '$current_id'";
            $objDbSelect->Execute($sql);
            $objResponse->addScript("fmfrmmanager_DeactiveStatus($id);");
            $objResponse->addScript("fm_obj.resetRoom($id);");
            $objResponse->addScript("$('#fmfrmmanager_div_$id').find('.trProduct').remove();");
        }
        $objResponse->addScript('changeWaiting(1);');
        $objResponse->addScript("fm_calActiveTableByTableType();");
        $objResponse->addScript("$('#fmfrmmanager_divCancel').dialog('close');");
    }else{
      $objResponse->addScript("fmfrmmanager_reloadform('Phòng này không hoạt động!');");     
    }
    return $objResponse->getXML();  
 }
 function fmmanager_deleteproduct($current_id,$pro_id){
    
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $sqlcheck = "select count(id) as cnt from fm_current_book$tbl_postfix where id = '$current_id' and flgcal=0 and flg_cancel=0 ";
    $arrChk=$objDbSelect->GetArray($sqlcheck);

    if($arrChk[0]['cnt']==1){
       $sql = "delete from cus_history_product$tbl_postfix  where general_id = '$current_id' and product_id = '$pro_id'";
        $objDbSelect->Execute($sql);
        $objResponse->addScript('changeWaiting(1);');
    }else{
      $objResponse->addScript("fmfrmmanager_reloadform('Phòng này không hoạt động!');");     
    }
    return $objResponse->getXML();  
 }

    
?>
